package com.qidian.buy.item.service.impl;

import com.qidian.buy.item.service.ItemService;
import com.qidian.buy.util.pojo.QdResult;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.*;

/**
 * Author: 戴着假发的程序员
 * Date: 2024-05-14 13:36
 * company: 起点编程
 **/
@Service
public class ItemServiceImpl implements ItemService {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${GOODS_URL}")
    private String goodsUrl;
    @Value("${STATIC_FILE_DIR}")
    private String staticFileDir;
    @Override
    public void getStaticForDetail(Long itemId) {
        // 发送远程请求
        QdResult result = restTemplate.getForObject(goodsUrl + "/item/detail?itemId=" + itemId, QdResult.class);
        if(result.getData() == null){
            return;
        }
        LinkedHashMap item = (LinkedHashMap) result.getData();
        Map data = new HashMap();
        data.put("item",item);
        Writer writer = null;
        // 生成静态页面
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        try {
            Template template = configuration.getTemplate("page.ftlh");
            // 准备输出流
            writer = new FileWriter(staticFileDir + "\\" + itemId + ".html");
            template.process(data,writer);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (TemplateException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                if (writer != null)
                    writer.close();
            }catch (IOException ex){
                throw new RuntimeException(ex);
            }
        }
    }
}
